#!/usr/bin/python

import os,sys,time,string,SocketServer
import ConfigParser
import socket,sys,time,os

def main ():
	cfgfile = open ('d:/hldscmd/config.ini','rw') ## read config file
	lines = cfgfile.readlines()
	for i in lines:
		if i[0] == ';':
			pass
		else:
			params = string.split(i,';')
			port  = params[0]
			start_map = params[1]
			maxplayers = params[2]
			csconfigfile =  params[3]
			mapcyclefile = params[4]		
			# Run hlserver
			os.spawnl(os.P_NOWAIT,'d:/hldscmd/hldsdaemon.exe','d:/hldscmd/hldsdaemon.exe',port,start_map,maxplayers,csconfigfile,mapcyclefile)
			#print os.popen('d:/hldscmd/hldsdaemon.exe %s %s %s %s %s' % (port,start_map,maxplayers,csconfigfile,mapcyclefile))
			time.sleep(2)
	cfgfile.close()
	run_linstenserver ()

def run_linstenserver ():
	# Create a socket
	sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	# Ensure that you can restart your server quickly when it terminates
	sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
	# Set the client socket's TCP "well-known port" number
	listenport = 27376
	sock.bind(('', listenport))
	# Set the number of clients waiting for connection that can be queued
	sock.listen(5)
	# loop waiting for connections (terminate with Ctrl-C)
	print 'Server listening'
	CL = CmdLine()
	try:
		while 1:
		        newSocket, address = sock.accept(  )
		       # print '%s' % (time.ctime(time.time())
			print "Connected from", address[0],'at',time.ctime(time.time())
		        # loop serving the new client
		        try:
				newSocket.send('needpasswd')
				receivedData = newSocket.recv(1024)
				if not receivedData: break
				if CL.cmd_access(receivedData,address[0]):  ## Check Access
					newSocket.send('Access denied')
					print "Disonnected from", address[0],'at',time.ctime(time.time())
					newSocket.close( )
					continue
				else:
					newSocket.send('Access OK')
			except socket.error:
				print 'connection closed by client'
				print "Disonnected from", address[0],'at',time.ctime(time.time())
				newSocket.close()
				continue
			while 1: ## Wait cmd
				try:

					newSocket.send('wait_cmd')
					receivedData = newSocket.recv(1024)
					print 'New RECV Data ;',receivedData
					if receivedData == 'quit':
						newSocket.send('bye')
						print "Disonnected from", address[0],'at',time.ctime(time.time())
						newSocket.close()
						break
					if receivedData == 'status':
						## return job ststus , and Send Some thing to Client
						pass
					if receivedData == 'add':
						## add new hlds server
						newSocket.send('add_ready')
						receivedData = newSocket.recv(1024)
						paramsreceived =receivedData.split(';')
						port  = paramsreceived[0]
						start_map = paramsreceived[1]
						maxplayers = paramsreceived[2]
						csconfigfile =  paramsreceived[3]
						mapcyclefile = paramsreceived[4]	
						os.spawnl(os.P_NOWAIT,'d:/hldscmd/hldsdaemon.exe','d:/hldscmd/hldsdaemon.exe',port,start_map,maxplayers,csconfigfile,mapcyclefile)
				except socket.error:
					print 'connection closed by client'
					print "Disonnected from", address[0],'at',time.ctime(time.time())
					newSocket.close()
					break
					
	finally:
		sock.close()
class CmdLine:
	def __init__ (self):
		self.src_ip = ['127.0.0.1']
		self.password = 'spilot'
	def cmd_access (self,passwd,srcip):
		if (passwd == self.password) and (srcip in self.src_ip):
			return 0
		else:
			return 1
	def cmd_start (self,cmdline):
		pass
	def cmd_quit (self,cmdline):
		pass
	def cmd_ststus (self,cmdline):
		pass	

if __name__ ==  '__main__':
	main()